有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java自定义listview,视图问题

我是安卓 studio中的新手,我试图创建自定义listview,问题是它创建了错误的列表,就像

Name
Name
------
Surname
Surname
-----

。。。重复

我想做的是:

Name
Surname
-------

我的代码是:

    protected void onResume() {
    DBHelper db = new DBHelper(this);
    ArrayList<String> names = new ArrayList<String>();

    for (int i = 0; i < db.getAllContacts().size(); i++) {
        names.add(db.getAllContacts().get(i).getName());
                names.add(db.getAllContacts().get(i).getEmail());

    }
        ArrayAdapter adapter = new custom_row(this, names);
        listView_allContacts.setAdapter(adapter);

        super.onResume();
    }

这里怎么了?提前谢谢

我的自定义行代码:

公共类自定义_行扩展ArrayAdapter{

public custom_row(Context context, ArrayList<String> names) {
    super(context, R.layout.custom_cell, names);

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater peoInf = LayoutInflater.from(getContext());
    View customView = peoInf.inflate(R.layout.custom_cell, parent , false);
    String singlePeople = getItem(position);
    TextView name_text = (TextView) customView.findViewById(R.id.name_text);
    TextView email_text = (TextView) customView.findViewById(R.id.email_text);

    name_text.setText(singlePeople);
    email_text.setText(singlePeople);
    return customView;
}

}


共 (1) 个答案

  1. # 1 楼答案

    你需要两个不同的ArrayList,一个用于姓名,一个用于电子邮件

    试试这个

    ArrayList<String> list;
    
    public custom_row(Context context, ArrayList<String> names, ArrayList<String> email) {
        super(context, R.layout.custom_cell, names);
        list = email;
    
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater peoInf = LayoutInflater.from(getContext());
        View customView = peoInf.inflate(R.layout.custom_cell, parent , false);
        String singlePeople = getItem(position);
        String email = list.get(position);
        TextView name_text = (TextView) customView.findViewById(R.id.name_text);
        TextView email_text = (TextView) customView.findViewById(R.id.email_text);
    
         name_text.setText(singlePeople);
        email_text.setText(email);
        return customView;
    }